package com.gdut.simple.view.activity.explore;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import com.gdut.simple.R;
import com.gdut.simple.contract.PublishContract;
import com.gdut.simple.data.entity.User;
import com.gdut.simple.event.RxBus;
import com.gdut.simple.event.SquareEvent;
import com.gdut.simple.presenter.PublishPresenter;
import com.gdut.simple.view.activity.common.PhotoPickActivity;
import com.gdut.simple.view.activity.common.PhotoPreviewActivity;
import com.gdut.simple.view.adapter.LocalImageGridAdapter;
import com.gdut.simple.view.adapter.base.AbsRecyclerAdapter;
import com.gdut.simple.view.basic.AbsBasicActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;

public class PublishActivity extends AbsBasicActivity implements PublishContract.View {

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_input_content_text)
    EditText mInputContentText;
    @BindView(R.id.id_image_view)
    RecyclerView mImageGridView;
    @BindView(R.id.id_location_check_button)
    CheckBox mLocationCheckBox;

    @OnClick(R.id.id_show_location_check_layout)
    void selectShowLocation() {
        if (isShowLocation) {
            isShowLocation = false;
            mLocationCheckBox.setChecked(false);
        } else {
            isShowLocation = true;
            mLocationCheckBox.setChecked(true);
        }
    }

    private PublishContract.Presenter mPublishPresenter;
    private List<String> mImagePath;
    private LocalImageGridAdapter mImageGridAdapter;
    private boolean isShowLocation = false;
    private static final int PHOTO_REQUEST_CODE = 100;

    private static final String ADD_IMAGE_PATH = "file:///android_asset/add_image.png";
    private static final int DEAFULT_SELECTED_COUNT = 9;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_publish_post);
        ButterKnife.bind(this);
        initToolbar();
        initImageGridView();
        new PublishPresenter(this);
    }

    private void initToolbar() {
        mToolbar.setTitle(R.string.publish);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initImageGridView() {
        mImagePath = new ArrayList<>(DEAFULT_SELECTED_COUNT);
        mImagePath.add(ADD_IMAGE_PATH);
        mImageGridAdapter = new LocalImageGridAdapter(this, mImagePath);
        mImageGridView.setLayoutManager(new GridLayoutManager(this, 4));
        mImageGridView.setItemAnimator(new DefaultItemAnimator());
        // mImageGridView.addItemDecoration(new GridSpacingItemDecoration(3, 5, true));
        mImageGridView.setAdapter(mImageGridAdapter);
        mImageGridAdapter.setOnItemClickListener(new AbsRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                if (position == mImagePath.size() - 1 && mImagePath.get(position).equals(ADD_IMAGE_PATH)) {
                    PhotoPickActivity.startActivityForResult(PublishActivity.this, PHOTO_REQUEST_CODE, RESULT_OK, getSelectedCount());
                } else {
                    PhotoPreviewActivity.startActivity(PublishActivity.this, getTempList(), position);
                }
            }

            @Override
            public boolean onLongClick(View view, int position) {
                if (position == mImagePath.size() - 1 && mImagePath.get(position).equals(ADD_IMAGE_PATH)) {
                    return false;
                }
                mImagePath.remove(position);
                mImageGridAdapter.notifyItemRemoved(position);
                checkSelectedCount();
                return true;
            }
        });
    }

    private int getSelectedCount() {
        return DEAFULT_SELECTED_COUNT - mImagePath.size() + 1;
    }

    private void checkSelectedCount() {
        if (mImagePath.size() >= DEAFULT_SELECTED_COUNT + 1) {
            mImagePath.remove(mImagePath.size() - 1);
            mImageGridAdapter.notifyItemRemoved(mImagePath.size() - 1);
        } else {
            if (mImagePath.get(mImagePath.size() - 1).equals(ADD_IMAGE_PATH)) {
                return;
            }
            mImagePath.add(ADD_IMAGE_PATH);
            mImageGridAdapter.notifyDataSetChanged();
        }
    }

    private ArrayList<String> getTempList() {
        ArrayList<String> temp = (ArrayList<String>) mImagePath;
        if (temp.get(mImagePath.size() - 1).equals(ADD_IMAGE_PATH)) {
            temp.remove(mImagePath.size() - 1);
        }
        return temp;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_publish, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_public:
                mPublishPresenter.publish();
                break;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_CODE:
                    if (data != null) {
                        ArrayList<String> images = data.getStringArrayListExtra("data");
                        if (images != null && images.size() > 0) {
                            mImagePath.addAll(mImagePath.size() - 1, images);
                            mImageGridAdapter.notifyDataSetChanged();
                            checkSelectedCount();
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public User getUser() {
        return BmobUser.getCurrentUser(User.class);
    }

    @Override
    public String[] getImagePaths() {
//        final String[] paths = new String[mImagePath.size()];
//        for (int i = 0; i < mImagePath.size(); i++) {
//            paths[i] = String.valueOf(mImagePath.get(i));
//        }
        return getTempList().toArray(new String[mImagePath.size()]);
    }

    @Override
    public String getContent() {
        return mInputContentText.getText().toString();
    }

    @Override
    public void next() {
        RxBus.getDefault().post(new SquareEvent());
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 100);
    }

    @Override
    public void setPresenter(@NonNull PublishContract.Presenter presenter) {
        this.mPublishPresenter = presenter;
    }
}
